export default `<template>
<div class="map" id="map"></div>
</template>

<script>
import "ol/ol.css";
import Draw from "ol/interaction/Draw";
import Map from "ol/Map";
import View from "ol/View";
import TileArcGISRest from "ol/source/TileArcGISRest";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource, Cluster } from "ol/source";
import {
Circle as CircleStyle,
Fill,
Stroke,
Style,
Text,
Icon
} from "ol/style";
import Point from "ol/geom/Point";
import Feature from "ol/Feature";

import mapData from "./data.js";
import pointImg from "@/images/device.png";
import CONSTANT from "@/config/constant.js";

const SEARCH_RADIUS = 200;

export default {
name: "polygonSearch",

data() {
  return {
    map: null,
    sourceCluster: null, //点位图层
    drawSource: null,
    drawVector: null,
    shape: null,
    selectedFeatures: [] //画图监所到的图层
  };
},

methods: {
  init() {
    //初始化地图
    this.map = new Map({
      layers: [
        new TileLayer({
          source: new TileArcGISRest({
            url: CONSTANT.GIS_URL
          })
        })
      ],
      target: "map",
      view: new View({
        center: [113.0567, 23.67537],
        maxZoom: 18,
        minZoom: 8,
        zoom: 13,
        projection: "EPSG:4326"
      })
    });

    this.showPoints();

    this.addDrawLayer();
  },

  // 展示聚合点位
  showPoints() {
    // 聚合图层数据源
    this.sourceCluster = new Cluster({
      distance: 100,
      source: new VectorSource({
        features: []
      })
    });

    const vectorLayer = new VectorLayer({
      source: this.sourceCluster,
      style: feature => {
        return this.setClusterStyle(feature);
      }
    });

    let features = [];
    mapData.forEach(item => {
      if (item.gps_x != "" && item.gps_y != "") {
        let newObj = Object.assign({}, item);
        newObj.geometry = new Point([Number(item.gps_x), Number(item.gps_y)]);
        features.push(new Feature(newObj));
      }
    });
    this.sourceCluster.getSource().addFeatures(features);
    this.map.addLayer(vectorLayer);

    /* 
      mapData是数组，每一项结构：
      {
          "domain_id": 10000029,
          "domain_name": "深圳市第一看守所",
          "domain_type_name": "看守所",
          "gps_x": "113.0131",
          "gps_y": "23.71433",
          "count": 0,
          "channel_id": "",
          "group_idx": 1
      } */
  },

  // 增加绘画图层
  addDrawLayer() {
    this.drawSource = new VectorSource({ wrapX: false });
    this.drawVector = new VectorLayer({
      source: this.drawSource
    });
    this.map.addLayer(this.drawVector);

    this.drawSquare();
  },

  //绘制多边形
  drawSquare() {
    this.shape = new Draw({
      source: this.drawSource,
      type: "Polygon",
      stopClick: true
    });

    this.map.addInteraction(this.shape);

    //绘画开始
    this.shape.on("drawstart", data => {
      this.selectedFeatures.splice(0, this.selectedFeatures.length);
    });

    //监听绘画结束
    this.shape.on("drawend", evt => {
      var polygon = evt.feature.getGeometry();
      var extent = polygon.getExtent();
      var features = this.sourceCluster
        .getSource()
        .getFeaturesInExtent(extent); //先缩小feature的范围
      for (var i = 0; i < features.length; i++) {
        var newCoords = features[i].getGeometry().getCoordinates();
        const points = polygon.getCoordinates();
        if (this.insidePolygon(points[0], newCoords)) {
          this.selectedFeatures.push(features[i]);
        }
      }

      alert("选择的设备数：" + this.selectedFeatures.length);
      console.log(JSON.stringify(this.selectedFeatures,null,4))
    });
  },

  /**
   *  判断一个点是否在多边形内部
   *  @param points 多边形坐标集合
   *  @param testPoint 测试点坐标
   *  返回true为真，false为假
   *  */
  insidePolygon(points, testPoint) {
    var x = testPoint[0],
      y = testPoint[1];
    var inside = false;
    for (var i = 0, j = points.length - 1; i < points.length; j = i++) {
      var xi = points[i][0],
        yi = points[i][1];
      var xj = points[j][0],
        yj = points[j][1];

      var intersect =
        yi > y != yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;
      if (intersect) inside = !inside;
    }
    return inside;
  },

  //设置聚合图层的样式
  setClusterStyle(feature) {
    var features = feature.get("features");
    var size = features.length;
    var style;
    if (size == 1) {
      style = [
        new Style({
          image: new Icon({
            src: pointImg
          })
        })
      ];
    } else {
      style = new Style({
        image: new CircleStyle({
          radius: 18,
          stroke: new Stroke({
            color: "#fff"
          }),
          fill: new Fill({
            color: "#3399CC"
          })
        }),
        text: new Text({
          font: "15px sans-serif",
          text: size.toString(),
          fill: new Fill({
            color: "#fff"
          })
        })
      });
    }
    return style;
  }
},

mounted() {
  this.init();
}
};
</script>

<style lang="less" scoped>
.map {
height: 100%;
}
</style>
`